package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.entity.SysTenant;
import com.evaluation.kexingcp.admin.service.SysTenantService;
import com.evaluation.kexingcp.admin.service.SysUserService;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.data.tenant.TenantBroker;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.common.security.annotation.Inner;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationGeneralResultEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTaskEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTaskUserRelEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationTeamReportTemplatesEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 任务名称
 *
 * @author pig
 * @date 2024-07-12 09:48:56
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/evaluationTask" )
@Tag(description = "evaluationTask" , name = "任务名称管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EvaluationTaskController {

    private final EvaluationTaskService evaluationTaskService;
    private final EvaluationTaskUserRelService evaluationTaskUserRelService;
    private final RestTemplate restTemplate;
    private final SysUserService sysUserService;
    private final SysTenantService sysTenantService;
    private final EvaluationTeamReportTemplatesService evaluationTeamReportTemplatesService;
    private final EvaluationGeneralResultService evaluationGeneralResultService;
    private final EvaluationScaleService evaluationScaleService;
    /**
     * 分页查询
     * @param page 分页对象
     * @param evaluationTask 任务名称
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('pigx_evaluationTask_view')" )
    public R getEvaluationTaskPage(@ParameterObject Page page, @ParameterObject EvaluationTaskEntity evaluationTask) {
        LambdaQueryWrapper<EvaluationTaskEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StrUtil.isNotBlank(evaluationTask.getTaskName()), EvaluationTaskEntity::getTaskName,evaluationTask.getTaskName());
        wrapper.eq(!Objects.isNull(evaluationTask.getIsTeamReportCompleted()), EvaluationTaskEntity::getIsTeamReportCompleted,evaluationTask.getIsTeamReportCompleted());
        wrapper.lt(EvaluationTaskEntity::getTaskLevel, 3);


        IPage<EvaluationTaskEntity> tasks = evaluationTaskService.page(page, evaluationTask);

        tasks.convert(task -> {
            task.setName(sysUserService.getUserVoByUsername(task.getCreateBy()).getName());
            task.setScales(evaluationTaskUserRelService.getTaskScales(task.getId()));

            if (task.getTaskLevel() == -1) {
                task.setUserCompletedCount((int)evaluationGeneralResultService.count(Wrappers.<EvaluationGeneralResultEntity>lambdaQuery().eq(EvaluationGeneralResultEntity::getTaskId, task.getId())));
                task.setScales(evaluationScaleService.getById(task.getScaleId()).getScaleName());
                JSONArray taskTimes = JSON.parseArray(task.getTaskTime());
                if (taskTimes.size() > 1) {
                    try {
                        LocalDateTime endTime = LocalDateTime.parse(taskTimes.getString(1).replace(" ", "T"));
                        if (endTime.isBefore(LocalDateTime.now())) {
                            task.setIsTeamReportCompleted(1);
                        }
                    } catch (Exception e) {
                        log.error("时间解析错误", e);
                    }
                }
            } else {
                if (task.getUserCount() == task.getUserCompletedCount()) {
                    task.setIsTeamReportCompleted(1);
                }
            }

            return task;
        });

        return R.ok(tasks);
    }


    /**
     * 通过id查询任务名称
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(evaluationTaskService.getById(id));
    }

    @GetMapping("/general/{id}/{tenantId}")
    @Inner(value = false)
    public R generalGetById(@PathVariable("tenantId") Long tenantId,  @PathVariable("id") Long id) {
        EvaluationTaskEntity task = TenantBroker.applyAs(tenantId, (tenantId1) -> evaluationTaskService.getById(id));

        if ( task != null && task.getTaskLevel() == - 1) {
            return R.ok(task);
        }
        return R.failed("任务不存在");
    }

    /**
     * 新增任务名称
     * @param evaluationTask 任务名称
     * @return R
     */
    @Operation(summary = "新增任务名称" , description = "新增任务名称" )
    @SysLog("新增任务名称")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationTask_add')" )
    public R save(@RequestBody EvaluationTaskEntity evaluationTask) {
        return R.ok(evaluationTaskService.save(evaluationTask));
    }

    /**
     * 修改任务名称
     * @param evaluationTask 任务名称
     * @return R
     */
    @Operation(summary = "修改任务名称" , description = "修改任务名称" )
    @SysLog("修改任务名称" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationTask_edit')" )
    public R updateById(@RequestBody EvaluationTaskEntity evaluationTask) {
        return R.ok(evaluationTaskService.updateById(evaluationTask));
    }

    /**
     * 通过id删除任务名称
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除任务名称" , description = "通过id删除任务名称" )
    @SysLog("通过id删除任务名称" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('pigx_evaluationTask_del')" )
    @Transactional
    public R removeById(@RequestBody Long[] ids) {
        // 清空任务关系表
        for (Long id : ids) {
            evaluationTaskUserRelService.remove(Wrappers.<EvaluationTaskUserRelEntity>lambdaQuery().eq(EvaluationTaskUserRelEntity::getTaskId,id));
        }

        return R.ok(evaluationTaskService.removeBatchByIds(CollUtil.toList(ids)));
    }

    /**
     * 导出excel 表格
     * @param evaluationTask 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('pigx_evaluationTask_export')" )
    public List<EvaluationTaskEntity> export(EvaluationTaskEntity evaluationTask,Long[] ids) {
        return evaluationTaskService.list(Wrappers.lambdaQuery(evaluationTask).in(ArrayUtil.isNotEmpty(ids), EvaluationTaskEntity::getId, ids));
    }

    @Inner(value = false)
    @GetMapping("/report/{tenantId}/{taskId}")
    public String report(@PathVariable("tenantId") Long tenantId, @PathVariable("taskId") Long taskId) {
        return TenantBroker.applyAs(tenantId, (tenantId1) -> {
            EvaluationTaskEntity task = evaluationTaskService.getById(taskId);
            return task.getTaskReportData();
        });
    }

    @GetMapping("/pdf/{tenantId}/{taskId}")
    public R pdf(@PathVariable("tenantId") Long tenantId, @PathVariable("taskId") Long taskId) {
        EvaluationTaskEntity task = evaluationTaskService.getById(taskId);
        SysTenant sysTenant = sysTenantService.getById(tenantId);
        ResponseEntity<String> response;
        EvaluationTeamReportTemplatesEntity templatesEntity = evaluationTeamReportTemplatesService.getOne(Wrappers.<EvaluationTeamReportTemplatesEntity>lambdaQuery()
                .eq(EvaluationTeamReportTemplatesEntity::getTemplateIsDefault, true).eq(EvaluationTeamReportTemplatesEntity::getTemplateType, sysTenant.getOrgType()));
        response = restTemplate.getForEntity("http://182.92.80.67:8686?url="+templatesEntity.getTemplateUrl()+"?params="+tenantId+"-"+taskId, String.class);
        String url = response.getBody();
        task.setTaskReportUrl(url);
        evaluationTaskService.updateById(task);

        return R.ok(url);
    }
}